import configStore from '@/stores/configStore'
import publicStore from '@/stores/publicStore'
import router from '../router'
import { isNull, isArray } from "./common"
import * as echarts from 'echarts'
import 'echarts-gl'
import 'echarts-liquidfill'
import chartPie from "./getOption/chartPie"
import chartPie3d from "./getOption/chartPie3d"
import chartLine from "./getOption/chartLine"
import chartBar from "./getOption/chartBar"
import chartScatter from "./getOption/chartScatter"
import chartBar3d from "./getOption/chartBar3d"

const Func = async(type:any, id:any, attr:any, data:any, pramas1:any, pramas2:any) => {
  let option:any
  switch (type) {
    case 'Pie':
      option = chartPie[id](attr, data, pramas1, pramas2)
      break;
    case 'Pie3d':
      option = chartPie3d[id](attr, data, pramas1, pramas2)
      break;
    case 'Line':
      option = chartLine[id](attr, data, pramas1, pramas2)
      break;
    case 'Bar':
      option = chartBar[id](attr, data, pramas1, pramas2)
      break;
    case 'Scatter':
      option = chartScatter[id](attr, data, pramas1, pramas2)
      break;
    case 'Bar3d':
      option = chartBar3d[id](attr, data, pramas1, pramas2)
      break;
    default:
    console.log('echart失败---')
    option = {}
  }
  return option
}

export default function ec() {
  const chartArr:any = []
  let time_3d:any = null
  // let mainId:any
  // let seriesData:any
  // 初始化
  const drawChart = (type:any, id:any, attr:any, data:any, pramas1:any, pramas2:any) => {
    let chartIndex = chartArr.findIndex((a:any)=> a.id == id)
    if(chartIndex == -1){
      console.log(id+'首次')
      initChart(type, id, attr, data, pramas1, pramas2)
    }else{
      console.log(id+'更新')
      reChart(type, id, attr, data, pramas1, pramas2)
    }
  }
  
  // 首次
  const initChart = async(type:any, id:any, attr:any, data:any, pramas1:any, pramas2:any) => {
    let myChart:any
    let option:any
    let dom:any = document.getElementById(id)
    if(!dom) return false
    myChart = echarts.init(dom)
    option = await Func(type, id, attr, data, pramas1, pramas2)
    let chart = {id: id, myChart: myChart, option: option, attr: Object.assign({}, attr), data: isArray(data)?[...data] : Object.assign({}, data)}
    chartArr.push(chart)
    myChart.setOption(option)
    setEvent(type, id, attr, data, pramas1, pramas2)
    if(!isNull(attr)) {
      setData(chart, data, true)
    }
  }

  // 更新
  const reChart = async(type:any, id:any, attr:any, data:any, pramas1:any, pramas2:any) => {
    let myChart:any
    let option:any
    let chart = chartArr.find((a:any)=> a.id == id)
    myChart = chart.myChart
    if(!isNull(attr) && JSON.stringify(chart.attr) != JSON.stringify(attr)){
      console.log(id+'属性重绘')
      option = await Func(type, id, attr, data, pramas1, pramas2)
      chart.option = option
      chart.attr = Object.assign({}, attr)
      chart.data = isArray(data)?[...data] : Object.assign({}, data)
      myChart.setOption(option, true) 
      if(!isNull(attr)) {
        setData(chart, data, true)
      }
    }else{
      if(JSON.stringify(chart.data) != JSON.stringify(data)){
        if(isNull(attr)){
          console.log(id+'数据重绘')
          option = await Func(type, id, attr, data, pramas1, pramas2)
          chart.option = option
          chart.data = isArray(data)?[...data] : Object.assign({}, data)
          myChart.setOption(option, true) 
        }else{
          console.log(id+'数据更新')
          chart.data = isArray(data)?[...data] : Object.assign({}, data)
          setData(chart, data, false)
        }
      }else{
        console.log(id+'无数据更新')
      }
    }
  }

  // 数据
  const setData = (chart:any, data:any, first:any) => {
    if(!data) return false
    console.log(chart.id + '数据填充')
    let myChart = chart.myChart
    let series = chart.option.series
    if(series[0].type == 'bar3D'){
      set3dData(chart, data, first)
    }else{
      myChart.setOption(data)
    }
  }

  // 3d数据
  const set3dData = (chart:any, data:any, first:any) => {
    let myChart = chart.myChart
    if(first){
      time_3d = setTimeout(() => {
        for(let i = 0; i< 2; i++){
          myChart.appendData({ seriesIndex: i, data: data.slice(i*18000, (i+1)*18000)})
        }
      }, 10)
    }else{
      for(let i = 0; i< 2; i++){
        myChart.appendData({ seriesIndex: i, data: data.slice(i*18000, (i+1)*18000)})
      }
    }
  }



  // 事件
  const setEvent = (type:any, id:any, attr:any, data:any, pramas1:any, pramas2:any) => {
    resize(type, id, attr, data, pramas1, pramas2)
    click(type, id, attr, data)
    dblclick(type, id, attr, data)
    datazoom(type, id, attr, data)
		georoam(type, id, attr, data)
  }

  // 单击
  const click = (type:any, id:any, attr:any, data:any) => {
    let chart = chartArr.find((a:any)=> a.id == id) 
    let myChart = chart.myChart
    myChart.off("click")
    myChart.getZr().on('click', function (params:any) {
      new Promise((resolve) => {
        console.log('单击触发')
        resolve(params);
      }).then((res) => {
        console.log('单击后...')
        if (params.topTarget) {
          var seriesIndex;          
          if (params.topTarget.type === 'ec-polyline') {
            seriesIndex = params.topTarget.parent.parent.__ecComponentInfo.index;
            console.log('点击线', seriesIndex)
          }
        }
        var pointInPixel= [params.offsetX, params.offsetY]
        if (myChart.containPixel('grid',pointInPixel)) {
          let pointInGrid = myChart.convertFromPixel({ seriesIndex: 0 }, pointInPixel)
          var xIndex=pointInGrid[0]
          var op=myChart.getOption()
          console.log('点击点', op.series[0].data[xIndex])
          // publicStore().chartDot = op.series[0].data[xIndex]
          publicStore().isTrue = !publicStore().isTrue
        }
      })
    })
  }

  // 双击
  const dblclick = (type:any, id:any, attr:any, data:any) => {
    let chart = chartArr.find((a:any)=> a.id == id) 
    let myChart = chart.myChart
    myChart.off("dblclick")
    myChart.getZr().on('dblclick', function (params:any) {
      new Promise((resolve) => {
        console.log('双击触发')
        if(id.indexOf('Bar3d') != -1) publicStore().isFalse = !publicStore().isFalse
        resolve(params);
      }).then((res) => {
        console.log(id+'双击后...')
        if(id.indexOf('Bar3d') != -1) drawChart(type, 'Bar3d', attr, data, {}, {})
      })
    })
  }

  // 缩放
  const datazoom = (type:any, id:any, attr:any, data:any) => {
    if(id != 'zoom') return
    let chart = chartArr.find((a:any)=> a.id == id) 
    let myChart = chart.myChart
    let lastdiff = 0
    myChart.on('datazoom', function (params:any) {
      let start = params.batch[0].start
      let end = params.batch[0].end
      let diff = end - start
      // mircodiff > 1，说明是放大而不是拖拽
      let mircodiff = Math.abs(diff - lastdiff)
      if (diff < 99 && mircodiff > 1) {
        // 放大之后的操作
        let option = myChart.getOption()
        option.series[0].symbolSize = 4 
        myChart.clear()
        myChart.setOption(option, true)
      }
      if (diff >= 99 && mircodiff > 1) {
        // 缩小回去的操作
        let option = myChart.getOption()
        option.series[0].symbolSize = 0
        myChart.clear()
        myChart.setOption(option, true)
      }
      lastdiff = diff
    })
  }

  // 地图缩放
  const georoam = (type:any, id:any, attr:any, data:any) => {
		let chart = chartArr.find((a:any)=> a.id == id)
		let myChart = chart.myChart
		myChart.on('georoam',function(params:any){
			if (params.dy == 0 && params.dx == 0) return
			var option = myChart.getOption();
			if(params.zoom!=null&&params.zoom!=undefined){
				if(params.componentType == "series"){
					option.geo[0].zoom=option.series[0].zoom;
					option.geo[0].center=option.series[0].center;
					option.geo[1].zoom=option.series[0].zoom;
					option.geo[1].center=option.series[0].center;
				}else{
					option.series[0].zoom=option.geo[0].zoom;
					option.series[0].center=option.geo[0].center;
					option.geo[1].zoom=option.geo[0].zoom;
					option.geo[1].center=option.geo[0].center;
				}
				myChart.clear()
			}else{
				if(params.componentType == "series"){
					option.geo[0].center=option.series[0].center;
					option.geo[1].center=option.series[0].center;
				}else{
					option.series[0].center=option.geo[0].center;
					option.geo[1].center=option.geo[0].center;
				}
			}
			myChart.setOption(option);
		})
  }

	// 自适应
  const resize = async(type:any, id:any, attr:any, data:any, pramas1:any, pramas2:any) => {
    let chart = chartArr.find((a:any)=> a.id == id) 
    window.addEventListener('resize', async() => {
      let myChart = chart.myChart
      let series = chart.option.series
      let data = chart.data
      let option = await Func(type, id, attr, data, pramas1, pramas2)
      option.series = series
      chart.option = option
      myChart.setOption(option)
      if(!isNull(attr)){
        setData(chart, data, true)
      }
      myChart.resize();
    }) 
  }

  // 销毁
  onUnmounted(() => {
    if(chartArr.length == 0) return 
    clearTimeout(time_3d)
    for(var i =0; i < chartArr.length; i++){
      chartArr[i].myChart.dispose()
    }
  })

  return {
    drawChart
  };
}
